package cn.tedu.mall.front.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.io.Serializable;

@Configuration
public class RedisConfiguration {

    /**
     * 如果使用默认的redisTemplate，序列化是key值为Object，value值为Object
     * hkey值为Object，hval值为Object
     * value一般存放的是对象数据
     * redisTemplate只保存和获取对象数据，如果是要处理string类型的计步器（incrby），hash类型的计步器（hincrby），请使用StringRedisTemplate
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate (RedisConnectionFactory redisConnectionFactory) {
        // 泛型不使用serializable，使用Object，保持和sso项目生成的用户redis数据一致
        // 否则有可能出现反序列化出异常
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(RedisSerializer.string());
        //使用java()序列化和反序列化，导致string相关的命令 计步器不能用了
        redisTemplate.setValueSerializer(RedisSerializer.java());
        // 项目中有可能用到hash结构，所以也要定义hash的序列化
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        redisTemplate.setHashValueSerializer(RedisSerializer.java());
        return redisTemplate;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate (RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
        stringRedisTemplate.setKeySerializer(RedisSerializer.string());
        stringRedisTemplate.setValueSerializer(RedisSerializer.string());
        return stringRedisTemplate;
    }

}
